import React from 'react'
import PropTypes from 'prop-types'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import Approve from '@components/ApprovePre/Index'
import StepOneInput from './DocumentApprove/StepOneInput'
import StepOneHistory from './DocumentApprove/StepOneHistory'
import StepTwoInput from './DocumentApprove/StepTwoInput'
import StepFourInput from './DocumentApprove/StepFourInput'
import StepTwoHistory from './DocumentApprove/StepTwoHistory'
import StepThreeHistory from './DocumentApprove/StepThreeHistory'
import StepFourHistory from './DocumentApprove/StepFourHistory'
import { message } from 'antd'
import { requestFiles } from '@js/request'
import { awaitWrap } from '@js/tool'

class DocumentApprove extends Component {
  state = {
    docTemplates: [],
    docTemplateMap: {}
  }

  // 文书模板
  getDocTemplate () {
    const hide = message.loading('获取文书模板', 120)
    this.$get('/api/vendor/file/getUserdefineNodoc')
      .then(res => {
        hide()
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        const map = {}
        res.data.forEach(li => {
          map[li.code] = li
        })
        this.setState({
          docTemplates: res.data,
          docTemplateMap: map
        })
      })
      .catch(() => hide())
  }

  // 根据模板code创建文书
  createDoc (bizid, codes) {
    const hide = message.loading('文书生成中', 120)
    return this.$post('/api/vendor/file/createByKeys', {
      filecodes: codes,
      caseid: this.props.caseDetail.id,
      bizid
    }).then(res => {
      hide()
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      return res.data
    }).catch(e => hide())
  }

  async stepOneBeforeSubmit (instance, data) {
    const vars = data.vars || {}
    vars.case_documentid = await this.createDoc(instance.id, data.code)
    vars.case_document_code = data.code
    vars.case_document_name = data.title
    delete data.code
    delete data.title
    return data
  }

  async stepTwoBeforeSubmit (instance, data) {
    let fileid = ''
    const file = data.file ? data.file.fileList : []
    if (file.length) {
      const hide = message.loading('文件上传中', 120)
      const [e, d] = await awaitWrap(requestFiles(file))
      hide()
      if (e) {
        return message.warning(e.message)
      }
      fileid = d.map(li => li.id).join()
    }
    delete data.file
    data.vars.other_fileid = fileid
    return data
  }

  async stepThreeToFiveBeforeSubmit (instance, data) {
    let fileid = ''
    const file = data.file ? data.file.fileList : []
    if (file.length) {
      const hide = message.loading('文件上传中', 120)
      const [e, d] = await awaitWrap(requestFiles(file))
      hide()
      if (e) {
        return message.warning(e.message)
      }
      fileid = d.map(li => li.id).join()
    }
    delete data.file
    data.vars.target_fileid = fileid
    return data
  }

  // 阅读文档
  readDoc (id) {
    this.$readerFileById(id, this.props.caseDetail.id)
  }

  componentDidMount () {
    this.$getFileList(this.props.caseDetail.id)
    this.getDocTemplate()
  }

  beforeSubmit (instance, data) {
    switch (instance.currentStep.step_key) {
      case 'liushuihaoanjianwenshu011':
        return this.stepOneBeforeSubmit(instance, data)
      case 'liushuihaoanjianwenshu01':
        return this.stepTwoBeforeSubmit(instance, data)
      case 'liushuihaoanjianwenshu03':
      case 'liushuihaoanjianwenshu04':
      case 'liushuihaoanjianwenshu05':
        return this.stepThreeToFiveBeforeSubmit(instance, data)
      default:
        return data
    }
  }

  // 渲染当前操作步骤线上部分
  renderCurrentStepLineTop (formRef, instance, renderFn) {
    switch (instance.currentStep.step_key) {
      case 'liushuihaoanjianwenshu011':
        return <StepOneInput instance={instance} userInfo={this.props.userInfo} caseDetail={this.props.caseDetail} formRef={formRef} dictionaries={this.state.dictionaries} docTemplates={this.state.docTemplates} docTemplateMap={this.state.docTemplateMap} />
      case 'liushuihaoanjianwenshu01':
        return <StepTwoInput instance={instance} userInfo={this.props.userInfo} caseDetail={this.props.caseDetail} formRef={formRef} />
      case 'liushuihaoanjianwenshu03':
      case 'liushuihaoanjianwenshu04':
      case 'liushuihaoanjianwenshu05':
        return <StepFourInput instance={instance} userInfo={this.props.userInfo} caseDetail={this.props.caseDetail} formRef={formRef} />
      default:
        return renderFn()
    }
  }

  // 渲染历史
  renderHistory (action, renderFn, instance, renderDocument) {
    const key = action.step_key
    // const isDisagree = action.opt_add === 'disagree'
    switch (key) {
      case 'liushuihaoanjianwenshu011':
        return <StepOneHistory key={action.id} userInfo={this.props.userInfo} instance={instance} action={action} renderDocument={renderDocument} readDoc={c => this.readDoc(c)} />
      case 'liushuihaoanjianwenshu01':
        return <StepTwoHistory key={action.id} userInfo={this.props.userInfo} instance={instance} action={action} renderDocument={renderDocument} />
      case 'liushuihaoanjianwenshu02':
        return <StepThreeHistory key={action.id} userInfo={this.props.userInfo} instance={instance} action={action} renderDocument={renderDocument} />
      case 'liushuihaoanjianwenshu03':
      case 'liushuihaoanjianwenshu04':
      case 'liushuihaoanjianwenshu05':
        return <StepFourHistory key={action.id} userInfo={this.props.userInfo} instance={instance} action={action} renderDocument={renderDocument} />
    }
    return renderFn(action)
  }

  render () {
    return (
      <div>
        <Approve
          caseDetail={this.props.caseDetail}
          flowKey='liushuihaoanjianwenshu'
          afterAction={(instance, action) => {
            this.props.refreshCaseData()
            this.$getFileList(this.props.caseDetail.id)
          }}
          renderCurrentStepLineTop={(...params) => this.renderCurrentStepLineTop(...params)}
          beforeSubmit={(...params) => this.beforeSubmit(...params)}
          renderHistory={(h, renderFn, instance, renderDocument) => this.renderHistory(h, renderFn, instance, renderDocument)}
          creatable={this.props.editable}
          multiply
        />
      </div>
    )
  }
}

DocumentApprove.propTypes = {
  caseDetail: PropTypes.object,
  // active: PropTypes.bool,
  // refreshCaseData: PropTypes.func
  editable: PropTypes.bool
  // fileList: PropTypes.array
  // getFileList: PropTypes.func
}
DocumentApprove.defaultProps = {
  caseDetail: {},
  active: false,
  refreshCaseData: () => {},
  editable: false,
  fileList: [],
  getFileList: () => {}
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(DocumentApprove)
